package org.example.service.market;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.dao.dao.market.CBusinessDao;
import org.example.dao.dao.user.AuUserRoleDao;
import org.example.dao.entity.market.CBusiness;
import org.example.dao.entity.user.AuUserRole;
import org.example.exception.AuthException;
import org.example.skytool.commom.ContextUtil;
import org.example.skytool.commom.IdWorker;
import org.example.skytool.commom.RegexUtils;
import org.example.skytool.security.EncodeUtil;
import org.example.utils.oaa.RedisBusinessService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * @author xluo
 * @date 2023/10/30 10:03
 */

@Service
public class BusinessService {

    @Resource
    private CBusinessDao cBusinessDao;

    @Resource
    private ContextUtil contextUtil;

    @Resource
    private IdWorker idWorker;

    @Resource
    private RedisBusinessService redisBusinessService;

    @Resource
    private AuUserRoleDao auUserRoleDao;

    /**
     * 新增商户
     */
    public CBusiness addBusiness(CBusiness business) {
        boolean isPhone = RegexUtils.checkPhone(business.getPhone());
        if (!isPhone) {
            throw new AuthException("电话格式错误");
        }

        CBusiness usernameIsValid = cBusinessDao.selectOne(new LambdaQueryWrapper<CBusiness>()
                .eq(CBusiness::getUsername, business.getUsername()));
        if (usernameIsValid != null) {
            throw new AuthException("用户名重复");
        }

        business.setPassword(EncodeUtil.encrypt(business.getPassword()));

        LambdaQueryWrapper<CBusiness> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CBusiness::getUsername, business.getUsername());
        lambdaQueryWrapper.eq(CBusiness::getPassword, business.getPassword());
        CBusiness oldBusiness = cBusinessDao.selectOne(lambdaQueryWrapper);
        if(oldBusiness != null &&
                Objects.equals(oldBusiness.getUsername(), business.getUsername()) &&
                Objects.equals(oldBusiness.getPassword(), business.getPassword())) {
            business = oldBusiness;
            oldBusiness.setIsValid(1);
            cBusinessDao.updateById(oldBusiness);
        } else {
            business.setId(idWorker.nextId());
            cBusinessDao.insert(business);
            // 首次新增，构造权限
            AuUserRole defaultUserRole = createDefaultUserRole(business.getId());
        }
        return business;
    }

    /**
     * 分页查询
     */
    public IPage<CBusiness> getBusiness(Long limit, Long start) {
        LambdaQueryWrapper<CBusiness> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        return cBusinessDao.selectPage(new Page<>(start, limit), lambdaQueryWrapper);
    }

    /**
     * 修改商户名
     */
    public CBusiness updateName(String name) {
        Long id = contextUtil.getId();
        CBusiness business = cBusinessDao.selectById(id);
        business.setName(name);
        business.setUpdateTime(new Date());
        cBusinessDao.updateById(business);
        redisBusinessService.delCacheToken(id.toString());
        return business;
    }

    /**
     * 修改商户电话
     */
    public CBusiness updatePhone(String phone) {
        boolean isPhone = RegexUtils.checkPhone(phone);
        if (!isPhone) {
            throw new AuthException("电话格式错误");
        }
        Long id = contextUtil.getId();
        CBusiness business = cBusinessDao.selectById(id);
        business.setPhone(phone);
        business.setUpdateTime(new Date());
        cBusinessDao.updateById(business);
        redisBusinessService.delCacheToken(id.toString());
        return business;
    }

    /**
     * 修改商户信息（管理）
     */
    public CBusiness updateInfo(CBusiness business) {
        boolean isPhone = RegexUtils.checkPhone(business.getPhone());
        if (!isPhone) {
            throw new AuthException("电话格式错误");
        }
        business.setUpdateTime(new Date());
        cBusinessDao.updateById(business);
        redisBusinessService.delCacheToken(business.getId().toString());
        return business;
    }

    /**
     * 删除商户
     */
    public void deleteBusiness(Long id) {
        CBusiness business = cBusinessDao.selectById(id);
        business.setIsValid(0);
        business.setUpdateTime(new Date());
        cBusinessDao.updateById(business);
        redisBusinessService.delCacheToken(id.toString());
    }

    public AuUserRole createDefaultUserRole(Long userId) {
        AuUserRole auUserRole = new AuUserRole();
        auUserRole.setId(idWorker.nextId());
        auUserRole.setUserId(userId);
        auUserRole.setRoleId(4L);
        auUserRole.setIsValid(1);
        auUserRole.setCreateTime(new Date());
        auUserRole.setUpdateTime(new Date());
        auUserRoleDao.insert(auUserRole);
        return auUserRole;
    }

}
